package com.example.common.handler;

import com.example.common.exception.BaseException;
import com.example.common.response.ServerCode;
import com.example.common.response.ServerResponse;
import javax.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description: 全局异常捕获处理
 * @Auther: Swain
 * @Date: 2021/1/11 16:48
 * @Version 1.0.0
 */
@RestControllerAdvice
public class CommonExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ServerResponse errorHandler(Exception ex) {
        logger.error("error:发生未知异常", ex);
        return ServerResponse.createByErrorCodeMessage(ServerCode.SYSTEM_ERROR);
    }

    @ResponseBody
    @ExceptionHandler(value = BaseException.class)
    public ServerResponse baseExceptionHandler(BaseException ex) {
        logger.error("error:发生" + ex.getClass().getName() + "异常", ex);
        return ServerResponse.createByErrorMessage(ex.getCode(), ex.getMsg());
    }


    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ServerResponse methodArgumentNotValidExceptionHandler(
        MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("参数校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getDefaultMessage());
        }
        String msg = sb.toString();
        return ServerResponse.createByErrorMessage(ServerCode.PARAMETER_ERROR.getCode(), msg);
    }


    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @ExceptionHandler({ConstraintViolationException.class})
    public ServerResponse constraintViolationExceptionHandler(ConstraintViolationException ex) {
        return ServerResponse.createByErrorMessage(ServerCode.PARAMETER_ERROR.getCode(),
            "参数校验失败:" + ex.getMessage() + ";");
    }


}
